import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hkzf/scpoed_model/room_filter.dart';
import 'package:hkzf/widgets/common_picker.dart';
import 'package:scoped_model/scoped_model.dart';

import 'data.dart';
import 'item.dart';

class FilterBar extends StatefulWidget {
  final ValueChanged<FilterBarResult> onchange;
  FilterBar({Key key, this.onchange}) : super(key: key);

  @override
  _FilterBarState createState() => _FilterBarState();
}

class _FilterBarState extends State<FilterBar> {
  bool isAreaActive = false;
  bool isRentActive = false;
  bool isPriceActive = false;
  bool isFilterActive = false;

  String areaId;
  String priceId;
  String rentTypeId;
  List<String> moreIds = [];

  // 初始化model里面的数据
  _getData() {
    Map<String, List<GeneralType>> dataList = new Map();
    dataList['roomTypeList'] = roomTypeList;
    dataList['orientedList'] = orientedList;
    dataList['floorList'] = floorList;
    ScopedModel.of<FilterBarModel>(context, rebuildOnChange: true).dataList =
        dataList;
  }

  @override
  void didChangeDependencies() {
    _onChange();
    super.didChangeDependencies();
  }

  @override
  void initState() {
    Timer.run(_getData);
    super.initState();
  }

  void _areaChange(context) {
    CommonPicker.showPicker(
      context: context,
      options: areaList.map((e) => e.name).toList(),
      value: areaId != null
          ? areaList.map((e) => e.id).toList().indexOf(areaId)
          : 0,
    )
        .then((index) => {
              if (index != null)
                {
                  setState(() {
                    areaId = areaList[index].id;
                    isAreaActive = true;
                  })
                }
            })
        .whenComplete(() => _onChange());
  }

  void _onChange() {
    var selectedList =
        ScopedModel.of<FilterBarModel>(context, rebuildOnChange: true)
            .selectedList;
    if (widget.onchange != null) {
      widget.onchange(FilterBarResult(
          areaId: areaId,
          rentTypeId: rentTypeId,
          priceId: priceId,
          moreIds: selectedList.toList()));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
        Item(
            title: '区域',
            isActive: isAreaActive,
            onTap: (context) {
              _areaChange(context);
            }),
        Item(title: '方式', isActive: false, onTap: (context) {}),
        Item(title: '租金', isActive: false, onTap: (context) {}),
        Item(
            title: '筛选',
            isActive: false,
            onTap: (context) {
              Scaffold.of(context).openEndDrawer();
            })
      ]),
      height: 41,
      decoration: BoxDecoration(
          border: Border(bottom: BorderSide(color: Colors.black12))),
    );
  }
}
